package com.zhang.hadoop.netty.netty.dubborpc.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.Callable;

/**
 * @author: zhang yufei
 * @createTime:2022/3/26 10:19
 * @description:
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter implements Callable {

    //上下文
    private ChannelHandlerContext context;

    //返回的结果
    private String result;

    //客户端调用方法时,传入的参数
    private String param;

    //与服务器的连接创建后,就会被调用(1)
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channelActive被调用");
        context = ctx;
    }

    //收到服务器的数据后,调用方法(4)
    @Override
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("channelRead被调用");
        result=msg.toString();
        notify();//唤醒等待线程
    }

    //(3)
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }

    //被代理对象调用,发送数据给服务器,->wait->等待被唤醒,->返回结果
    @Override
    public synchronized Object call() throws Exception {
        System.out.println("call-1被调用");
        context.writeAndFlush(param);
        //进行waiting
        wait();//等待channelRead方法获取到服务器的结果后,唤醒
        System.out.println("call-2被调用");
        return result; //服务方返回的结果
    }

    //设置参数(2)
    void setParam(String param){
        System.out.println("setParam被调用");
        this.param=param;
    }

}
